<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <el-form-item prop="processingstate" class="times">
          <el-radio-group v-model="queryParams.processingstate">
            <el-radio-button
              v-for="city in dict.type.warn_status"
              :label="city.value"
              :key="city.value"
              >{{ city.label }}</el-radio-button
            >
          </el-radio-group>
        </el-form-item>
        <!-- 预警点位名称 -->
        <el-form-item label="预警点位名称：" prop="segmentname">
          <el-input
            v-model="queryParams.segmentname"
            placeholder="请输入预警点位名称查询"
          ></el-input>
        </el-form-item>
        <!-- 报警时间 -->
        <el-form-item label="报警时间：" prop="alarmTime">
          <el-date-picker
            v-model="queryParams.alarmTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <!-- 预警类别 -->
        <el-form-item label="预警类别：" prop="warntype">
          <el-select
            style="width: 150px"
            clearable
            v-model="queryParams.warntype"
            placeholder="请选择"
          >
            <el-option
              v-for="item in dict.type.warn_type_data"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 报警类型 -->
        <el-form-item label="报警类型：" prop="warncategory">
          <el-select v-model="queryParams.warncategory" placeholder="请选择">
            <el-option
              v-for="item in dict.type.warn_class_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 报警级别 -->
        <el-form-item label="报警级别：" prop="warnlevel">
          <el-select v-model="queryParams.warnlevel" placeholder="请选择">
            <el-option label="一级" value="1"></el-option>
            <el-option label="二级" value="2"></el-option>
            <el-option label="三级" value="3"></el-option>
          </el-select>
        </el-form-item>
        <!-- 查询按钮 -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >查询</el-button
          >
        </el-form-item>
        <!-- 普通搜索按钮 -->
        <!-- <el-form-item>
          <el-button type="warning" @click="commonSearch">普通搜索</el-button>
        </el-form-item> -->
        <!-- 批量关闭按钮 -->
        <el-form-item>
          <el-button type="info" @click="batchClose">批量关闭</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="tableCard">
      <el-table
        :data="tableData"
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选框列 -->
        <el-table-column type="selection" width="50" align="center" />
        <!-- 预警点位名称 -->
        <el-table-column prop="segmentname" label="预警点位名称" />
        <!-- 预警级别 -->
        <el-table-column prop="warnlevel" label="预警级别">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.warnlevel === '1'" type="danger"
              >一级</el-tag
            >
            <el-tag v-if="scope.row.warnlevel === '2'" type="warning"
              >二级</el-tag
            >
            <el-tag v-if="scope.row.warnlevel === '3'" type="success"
              >三级</el-tag
            >
          </template>
        </el-table-column>
        <!-- 预警类型 -->
        <el-table-column
          prop="warntype"
          :formatter="formatDictLabel"
          label="预警类型"
        />
        <!-- 报警时间 -->
        <el-table-column prop="warntime" label="报警时间" />
        <!-- 监测因子 -->
        <el-table-column prop="itemname" label="监测因子" />
        <!-- 预警信息 -->
        <el-table-column
          show-overflow-tooltip
          prop="warnmessage"
          label="预警信息"
        />
        <el-table-column
          prop="controlSuggestions"
          label="管控建议"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.controlSuggestions }}
          </template>
        </el-table-column>
        <!-- 状态 -->
        <el-table-column prop="processingstate" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.processingstate === '0'" type="danger"
              >未处理</el-tag
            >
            <el-tag v-if="scope.row.processingstate === '1'" type="warning"
              >处理中</el-tag
            >
            <el-tag v-if="scope.row.processingstate === '2'" type="warning"
              >已处理</el-tag
            >
            <el-tag v-if="scope.row.processingstate === '3'">已关闭</el-tag>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="audit(scope.row)">审核</el-button>
            <!-- <el-button type="text" @click="viewDetails(scope.row)"
              >详情</el-button
            >
            <el-button type="text" @click="closeWarning(scope.row)"
              >关闭</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 审核弹窗 -->
    <el-dialog :title="'审核'" :visible.sync="dialogVisible" width="500px">
      <el-form ref="auditForm" :model="auditForm" label-width="80px">
        <el-form-item label="状态">
          <el-radio v-model="auditForm.status" label="2">通过</el-radio>
          <el-radio v-model="auditForm.status" label="3">关闭</el-radio>
        </el-form-item>
        <el-form-item label="说明">
          <el-input
            type="textarea"
            v-model="auditForm.description"
            rows="6"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getWarningList,
  updateWarning,
  updateWarningBatch,
  getWarningType,
} from "@/api/waterWarningAnalysis";
export default {
  name: "WarningMonitor",
  dicts: ["warn_status", "warn_type_data", "warn_class_type"],
  data() {
    return {
      tableHeight: window.innerHeight - 400,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processingstate: "0",
        segmentname: "",
        alarmTime: [], // 报警时间范围
        warntype: "", // 预警类别
        alertType: "", // 报警类型
        warnlevel: "", // 报警级别
      },
      total: 144, // 总条数
      tableData: [],
      ids: [], // 选中行的ID集合
      dgid: "",
      dialogVisible: false,
      auditForm: {
        status: "", // 存储审核状态（通过/关闭）
        description: "", // 存储说明内容
      },
      dictMap: {}, // 存储dictValue到dictLabel的映射
    };
  },
  created() {
    this.getWarningType();
  },
  mounted() {
    // 监听窗口大小变化，调整表格高度
    window.addEventListener("resize", this.handleResize);
    this.getList(); // 初始化加载表格数据
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    //预警类型的接口
    getWarningType() {
      getWarningType().then((res) => {
        this.dictMap = {};
        res.data.forEach((item) => {
          this.dictMap[item.dictValue] = item.dictLabel;
        });
      });
    },
    formatDictLabel(row, column, cellValue) {
      return this.dictMap[cellValue] || "-";
    },
    // 处理窗口大小变化
    handleResize() {
      this.tableHeight = window.innerHeight - 400;
    },

    // 表格多选框选中事件
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },

    // 分页-每页条数变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    // 分页-当前页变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 查询按钮事件
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 普通搜索按钮事件
    commonSearch() {
      // 普通搜索逻辑，这里简单处理为重置并查询
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        segmentname: "",
        alarmTime: [],
        warntype: "all",
        alertType: "all",
        warnlevel: "all",
      };
      this.getList();
    },

    // 批量关闭按钮事件
    batchClose() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择要关闭的预警项");
        return;
      }
      this.$confirm("确定批量关闭选中的预警项吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = this.ids.join(",");

          updateWarningBatch(params).then((res) => {
            console.log(res);
          });
          // 调用批量关闭接口
          this.$message.success("批量关闭成功");
          this.getList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },

    // 审核按钮事件
    audit(row) {
      this.auditForm = {
        // ...row,
        status: "", // 重置审核状态
        description: "", // 重置说明内容
      };
      this.dgid = row.id;

      this.dialogVisible = true;
    },

    // 查看详情
    viewDetails(row) {
      this.$message.info(`查看${row.segmentname}的预警详情`);
      // 实际应用中可跳转到详情页
      // this.$router.push({ path: '/warning/detail', query: { id: row.id } });
    },

    // 关闭预警
    closeWarning(row) {
      this.$confirm(`确定要关闭${row.segmentname}的预警吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 调用关闭预警接口
        this.$message.success("预警已关闭");
        this.getList();
      });
    },

    // 提交审核
    submitAudit() {
      if (!this.auditForm.status) {
        this.$message.warning("请选择审核状态");
        return;
      }
      let query = {
        id: this.dgid,
        status: this.auditForm.status,
        remark: this.auditForm.description,
      };
      updateWarning(query).then((res) => {
        if (res.code == 200) {
          // this.$message.success("审核成功");
          // 调用审核接口，传入this.auditForm数据
          this.$message.success("审核已提交");
          this.dialogVisible = false;
          this.getList();
        }
      });
    },

    // 获取表格数据（对接后端接口）
    getList() {
      // 示例：调用接口获取数据
      let query = JSON.parse(JSON.stringify(this.queryParams));
      delete query.alarmTime;
      query.beginTime = this.queryParams.alarmTime[0];
      query.endTime = this.queryParams.alarmTime[1];
      getWarningList(this.queryParams).then((res) => {
        console.log(">>>表格的数据", res);

        this.tableData = res.rows;
        this.total = res.total;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .queryForm {
    .el-card__body {
      padding: 10px 20px !important;
    }
    .el-form-item {
      margin: 10px 0 10px 10px;
    }
    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }
    .el-form-item__content {
      min-width: 200px;
    }
  }

  .tableCard {
    margin: 10px;
    .el-table {
      width: 100%;
      margin-bottom: 15px;
    }
  }

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
